package com.core.framework.freemarker;

import java.lang.reflect.Field;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.core.framework.freemarker.annotation.FtlField;
import com.core.framework.tools.ClassTools;
import com.core.log.Log;
import com.util.AppUtils;

import freemarker.template.Configuration;
import freemarker.template.TemplateModelException;
/**
 * 初始化FreeMarker模板数据  
 * @author 刘涛
 * @since Jun 19, 2012
 */
public class TemplateInit 
{
	Configuration config ;
	private static TemplateInit init;
	public synchronized static TemplateInit getInit()
	{
		if(init==null)
		{
			init = new TemplateInit();
		}
		return init;
	}
	public TemplateInit()
	{
		config = new Configuration();
	}
	public void  initTemplateOpBean()
	{
		Log.debug("模板数据初始化开始.....");
		Set<Class<?>> classSet = ClassTools.getClassTools().getClassSetByAnnotation(Service.class);
		//初始化模板函数操作信息  
		for(Class<?> cla : classSet)
		{
			try {
				if(cla.isAnnotationPresent(Service.class))
				{
					Service service = cla.getAnnotation(Service.class);
					Object obj = AppUtils.getBean(cla);
					String funName = service.value();
					Log.debug("......................>"+cla.getName());
					if(StringUtils.isNotBlank(funName))
					{
						config.setSharedVariable(funName, obj);
					}
					Field fields[] = cla.getFields();
				    for (Field f : fields) {
	                    if (f.getAnnotation(FtlField.class) != null) {
	                    	if(StringUtils.isNotBlank(f.getName()))
	                    	{
		                    	String fieldName =funName+"_"+f.getName();
		                    	config.setSharedVariable(fieldName, f.get(obj));
	                    	}
	                    }
	                }
				}
			} catch (TemplateModelException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		Log.debug("模板数据初始化结束..... 耗时："+System.currentTimeMillis());
	}
    public Configuration getConfig() {
		return config;
	}

	public void setConfig(Configuration config) {
		this.config = config;
	}

	protected Configuration createConfiguration() {
        return new Configuration();
    }
}
